﻿using Heroius.Extension;
using Heroius.Extension.Box;
using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace Heroius.QPDFShell
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }

        #region Window Movement

        bool Moving
        {
            get { return _moving; }
            set
            {
                _moving = value;
                OriginLocation = MousePosition;
            }
        }
        bool _moving = false;

        Point OriginLocation;

        private void PnlHead_MouseMove(object sender, MouseEventArgs e)
        {
            if (Moving)
            {
                var srcp = PointToScreen(e.Location);
                int LocX = this.Location.X + srcp.X - OriginLocation.X;
                int LocY = this.Location.Y + srcp.Y - OriginLocation.Y;
                OriginLocation = srcp;
                this.Location = new Point(LocX, LocY);
            }
        }

        private void PnlHead_MouseDown(object sender, MouseEventArgs e)
        {
            Moving = true;
        }

        private void PnlHead_MouseUp(object sender, MouseEventArgs e)
        {
            Moving = false;
        }

        private void PnlHead_MouseLeave(object sender, EventArgs e)
        {
            Moving = false;
        }

        #endregion

        #region File Decryption

        FileInfo Target;

        void DecryptFile()
        {
            try
            {
                ExeBox ebx = new ExeBox(new FileInfo("qpdf.exe"));
                ebx.ExecutionCompleted += ebx_ExecutionCompleted;
                int i = 1;
                string prefix = string.Format("{0}/{1}_decrypt", Target.DirectoryName, Target.Name.Remove(Target.Name.Length - 4));
                string ext = ".pdf";
                string newname = prefix + ext;
                bool Exist = File.Exists(newname);
                while (Exist)
                {
                    newname = prefix + i.ToString() + ext;
                    Exist = File.Exists(newname);
                    i++;
                }
                LbMe.Enabled = false;
                ebx.Start(string.Format("-decrypt \"{0}\" \"{1}\"", Target.FullName, newname));
            }
            catch (Exception ex)
            {
                MessageBox.Show(
#if DEBUG
                ex.Message,
#else
                "执行过程发生错误，可能是文件被破坏所致，请重新安装后重试。",
#endif
                "发生错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

                LbMe.Enabled = true;
            }
        }

        void ebx_ExecutionCompleted(object sender, ExeBox.ExecutionCompletedArgs e)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<object, ExeBox.ExecutionCompletedArgs>(ebx_ExecutionCompleted), sender, e);
            }
            else
            {
                switch (e.ExitStatus)
                {
                    case ExeBox.CompleteStatus.Finished:
                        MessageBox.Show("执行成功，请到源目录下查看。", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        break;
                    case ExeBox.CompleteStatus.CustomError:
                    case ExeBox.CompleteStatus.SystemError:
                        MessageBox.Show("执行过程发生错误，请联系开发者反馈问题。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        break;
                    default://do nothing for these will never happen
                        break;
                }
                LbMe.Enabled = true;
            }
        }

        private void LbMe_Click(object sender, EventArgs e)
        {
            DiaOpen.ShowDialog();
        }

        private void DiaOpen_FileOk(object sender, CancelEventArgs e)
        {
            Target = new FileInfo(DiaOpen.FileName);
            DecryptFile();
        }

        private void LbMe_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                FileInfo Fi = new FileInfo(((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString());
                if (Fi.Exists && Fi.Extension.ToUpper() == ".PDF")
                {
                    e.Effect = DragDropEffects.All;
                    Target = Fi;
                    return;
                }
            }
            e.Effect = DragDropEffects.None;
            Cursor = Cursors.No;
        }

        private void LbMe_DragLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Default;
        }

        private void LbMe_DragDrop(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.None;
            Cursor = Cursors.Default;
            DecryptFile();
        }

        #endregion

        private void BtnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            new FormAbout().ShowDialog();
        }
    }
}
